/*
 * @Author: liaoxin
 * @Date: 2022-03-08 17:34:24
 * @LastEditors: liaoxin
 * @LastEditTime: 2022-06-13 14:36:41
 * @FilePath: \personnelmanage\src\pages\CustomerManage\Customer\List\add\index.tsx
 */
import React from "react";
import { UdPageHeader, http, UdForm, validators } from '@/lib';
import { Select, Input, Form, message, Button, Icon, Spin, Empty, Modal } from 'antd';
import './index.scss'
import { BrandInfoEditTable } from "../../component/BrandInfoEditTable";
import apis from './../../../../../apis/UserManagement/index'
import { WrappedFormUtils } from "antd/lib/form/Form";
import { formUtils } from "@/lib/utils/formUtils";


export default class CustoemrAdd extends React.Component<any> {

  private form: WrappedFormUtils

  state = {
    customerNameOptions: [],
    customerInfo: {
      agentName: undefined,
      agentCode: undefined,
      address: undefined,
      contact: undefined,
      phone: undefined,
      // brandCode: undefined,
    },
    querying: false,
    keyWord: null,
  }

  //查询客户名称
  // private handleSearch = (val) => {
  //   if (val.length > 0) {
  //     this.setState({ querying: true })
  //     http.post(apis.DealerAccountMessage, { customerName: val }).then(res => {
  //       let data = res?.data?.agentMdm || []
  //       this.setState({ customerNameOptions: data.map(item => ({ value: item.sapCustomerCode, name: item.customerName, ...item })) })
  //     }).finally(() => this.setState({ querying: false }))
  //   }
  // }

  //客户名称改动
  private handleChange = (val) => {
    let customer = this.state.customerNameOptions.filter(item => item.value === val)
    this.setState({
      customerInfo: {
        agentName: customer[0]?.customerName,
        agentCode: customer[0]?.sapCustomerCode,
        address: customer[0]?.address,
        contact: customer[0]?.contacts[0]?.cusContactsName,
        phone: customer[0]?.contacts[0]?.cusContactsPhone,
        socialCode: customer[0]?.socialCreditCode,
        agentType: '经销商',
      }
    })
  }

  //提交表单
  private hendleSubmit = (tableData: any[]) => {
    console.log(tableData)
    this.form.validateFieldsAndScroll((error, values) => {
      values = formUtils.handleValues(values)
      console.log('values', values)
      if (!error && tableData.indexOf(false) === -1) {
        Modal.confirm({
          title: `新增客户`,
          content: `确认新增该客户吗？`,
          onOk: () => {
            const userList: any = []
            if (values.phone) {
              // 必须又手机号才将用户信息给后端，只有名称，不给用户数据。
              const userInfo: any = { cusContactsPhone: values.phone }
              if (values.contact) {
                userInfo.cusContactsName = values.contact
              }
              userList.push(userInfo)
            }
            const params = {
              brandList: tableData,
              ...values,
              userList: userList,
            }
            return http.post(apis.addCustomer, params).then(res => {
              message.success("新增成功！")
              sessionStorage.setItem('CreateBackList', 'true')
              let ZdParams = {
                brandCode: "",
                dealerCode: values.agentCode
              }
              tableData.forEach((item, index) => {
                setTimeout(() => {
                  ZdParams.brandCode = item.brandCode
                  http.post(apis.pushUpdateDealerZd, ZdParams).then(resp => {
                  })
                }, index * 3000);
              })
              this.props.history.goBack()
            })
          }
        })
      }
    })
  }

  querySelectData = (e: any) => {
    e.stopPropagation()
    const { keyWord } = this.state;

    if (!keyWord) return message.warning('请输入查询关键字')
    this.setState({ querying: true })
    http.post(apis.DealerAccountMessage, { customerName: keyWord }).then(res => {
      let data = res?.data?.agentMdm || []
      this.setState({ customerNameOptions: data.map(item => ({ value: item.sapCustomerCode, name: item.customerName, ...item })) })
    }).finally(() => this.setState({ querying: false }))
  }

  render() {
    return <div className="customer-mg-add-box">
      <UdPageHeader title="新增客户" onBack />
      <UdForm className="customer-add-form-box" items={[
        {
          id: 'agentName', label: '客户名称', rules: [validators.required], render: (
            <Select
              value={this.state.customerInfo?.agentName}
              placeholder="请输入客户名称搜索"
              showSearch
              defaultActiveFirstOption={false}
              // showArrow={false}
              filterOption={false}
              // onSearch={this.handleSearch}
              onSearch={(e: any) => this.setState({ keyWord: e })}
              onChange={this.handleChange}
              suffixIcon={(
                this.state.querying ? (
                  <Spin
                    style={{
                      marginTop: '-3px',
                    }}
                    size="small"
                  />
                ) : (
                  <Button
                    style={{
                      marginTop: '-6px',
                    }}
                    size="small"
                    type="link"
                    onClick={this.querySelectData}
                  >
                    查询
                  </Button>
                )
              )}
              className='ud-search-select'
              // notFoundContent={this.state.querying ? <Spin size="small" /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
              optionFilterProp="children"
              getPopupContainer={(triggerNode) => triggerNode.parentNode as HTMLElement}
            >
              {this.state.customerNameOptions.map((item, index) => <Select.Option key={index} value={item.value}>{item.name}</Select.Option>)}
            </Select>
          )
        },
        {
          id: 'agentCode', label: '客户编码', rules: [validators.required], render: () => {
            return <Input disabled />
          }
        },
        {
          id: 'agentType', label: '客户类型', rules: [validators.required], render: () => {
            return <Input disabled placeholder='经销商' />
          }
        },
        { id: 'address', label: '联系地址', rules: [validators.required, validators.max(100)] },
        { id: 'contact', label: '联系人', rules: [validators.userName, validators.max(10)] },
        { id: 'phone', label: '联系电话', rules: [validators.phoneCommonly] },
        { id: 'socialCode', label: '税号', rules: [validators.required, validators.max(20)] },
      ]}
        values={this.state.customerInfo}
        getForm={(form) => {
          this.form = form
        }}
        layout='vertical'
        labelCol={null}
        wrapperCol={null}
      />
      <BrandInfoEditTable
        history={this.props.history}
        getData={(data) => {
          this.hendleSubmit(data)
        }} />
    </div>
  }
}